package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

//实现上传文件的功能
@RestController
@Slf4j
@Api(tags = "通用接口")
@RequestMapping("/admin/common")
public class UploadController {
    //进行依赖注入
    @Autowired
    private AliOssUtil aliOssUtil;
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file){
        if(file.isEmpty()){
            return  Result.error("文件为空");
        }
        try{
            //获取文件的原始名称
            String originalFilename = file.getOriginalFilename();
            //生成唯一的文件名（防止命名冲突）
            //获取文件后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //生成新的文件名
            String objectName = UUID.randomUUID() + suffix;
            //调用AliOssUtil进行文件上传
            String fileUrl = aliOssUtil.upload(file.getBytes(),objectName);
            if(fileUrl != null){
                return Result.success(fileUrl);
            }else{
                return Result.error(MessageConstant.UPLOAD_FAILED);
            }
        }catch(Exception e){
            log.info("文件上传失败");
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }
}
